package com.hewep.support.excel;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.hewep.kit.CacheKit;
import com.hewep.kit.ConfigKit;
import com.hewep.kit.DateUtils;
import com.hewep.kit.TableKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class DefaultRowReader implements IRowReader {
	private String tableName;
	private String[] header = null;
	private List<Record> temp = new ArrayList<Record>();
	private ArrayBlockingQueue<Record> dataQueue = new ArrayBlockingQueue<Record>(2000);
	private int i =0;
	private boolean run = true;
	private Thread handler ;
	public DefaultRowReader(String tableName){
		this.tableName = tableName;
		
		this.handler = new Thread(){
			private String columns = TableKit.getColumns("datas");
			private String sql = TableKit.getInsertSql("datas");
			@Override
			public void run() {
				
				while(run){
					if(dataQueue.isEmpty()) continue;
					
					for (int j=0; j< 2000; j++) {
						try {
							// take 方法会阻塞 
							Record record = dataQueue.poll(2, TimeUnit.SECONDS);
							if(record == null){
								run = false;
								System.out.println("----"+run);
								break;
							}else{
								temp.add(record);
							}
						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("退出======"+dataQueue.size()+":::"+temp.size()+"::"+run);
							if(dataQueue.size()<=0){
								run = false;
								break;
							}
						}
					}
					
					Db.batch(sql, columns, temp, temp.size());
					i += temp.size();
					System.out.println(i+"::"+temp.size());
					temp.clear();
					
					if(!run){
						postProcess();
					}
				}
			}
		};
		this.handler.start();
	}
	
	/*
	 * 业务逻辑实现方法
	 */
	public void getRows(int sheetIndex, int curRow, List<String> rowlist) {
		// TODO Auto-generated method stub
		if(curRow == 0){
			header =  rowlist.toArray(new String[rowlist.size()]);
		}else{
			Record record = new Record();
			for (int i = 0; i < rowlist.size(); i++) { 
				String key = CacheKit.getColumnByRemark(tableName, header[i]);
				record.set(key, rowlist.get(i));
	        }  
			try {
				dataQueue.put(record);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		if(handler != null){
			//handler.interrupt();
		}
	}
	
	String orgTempColumns = TableKit.getColumns("org_temp");
	String orgTempSql = TableKit.getInsertSql("org_temp");
	String orgColumns = TableKit.getColumns("org");
	String orgSql = TableKit.getInsertSql("org");
	
	public void postProcess(){
		try {
			long l = System.currentTimeMillis();
			System.out.println("统计分析开始");
			String sql = "select orgName,orgTel, dealerCode,province,city,dist,filterDealerAddr,count(1) as num "+
						"from datas group by orgName,orgTel, dealerCode, province,city,dist, filterDealerAddr order by count(num), orgName";
			
			List<Record> records = Db.find(sql);
			
			Db.batch(orgTempSql, orgTempColumns, records, records.size());
			Thread.sleep(2000);
			String lastOrderNo = "HB-" + DateUtils.getCurrDateFormat("yyMMdd")+"-0000";
			DecimalFormat df = new DecimalFormat("0000");
			int sno = ConfigKit.getOrderNo("HB");
			Thread.sleep(1000);
			// 添加数量为 1 的记录
			List<Record> records1 = Db.find("select distinct a.* from org_temp a inner join datas b on  a.dealerCode = b.dealerCode where a.num = 1 order by  b.outModel,a.orgName");
			for (Record record : records1) {
				lastOrderNo = "HB-" + DateUtils.getCurrDateFormat("yyMMdd")+"-"+df.format(++sno); 
				record.set("code", lastOrderNo.replace("-", ""));
			}
			Db.batch(orgSql, orgColumns, records1, records1.size());
			Thread.sleep(1000);
			// 添加数量 大于 1 的记录
			records1 = Db.find("select * from org_temp where num >1 order by num,orgName");
			for (Record record : records1) {
				lastOrderNo = "HB-" + DateUtils.getCurrDateFormat("yyMMdd")+"-"+df.format(++sno); 
				record.set("code", lastOrderNo.replace("-", ""));
			}
			Db.batch(orgSql, orgColumns, records1, records1.size());
			Thread.sleep(2000);
			ConfigKit.updateOrderNo("HB",lastOrderNo);
			
			System.out.println("统计分析结束:"+((System.currentTimeMillis() -l)));
			isFinished = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private boolean isFinished = false;
	public boolean isFinished() {
		return isFinished;
	}

}